// cas_db1_h 型号电子称对接
import Vue from 'vue'

export default {

  uint8ArrayToStr(inputUnit8) {
    let arr = []
    for (let i = 0; i < inputUnit8.length; i++) {
      arr.push(inputUnit8[i])
    }
    return arr.join(',')
  },

  async connectSerial(cfg) {
    // 浏览器支持serial
    if ('serial' in navigator) {

      // 自动连接
      if (cfg.autoConnect) {
        let ports = await navigator.serial.getPorts()
        if (!ports || ports.length == 0) {
          cfg.connectFail()
          return
        }
        if (!ports || ports.length > 1) {
          Vue.prototype.$message({
            type: 'info',
            message: Vue.prototype.$tt('label_auto_weight_ports_to_many') // 电子称已连接
          })
          return
        }
        this.port = ports[0]
      }
      // 手动连接
      else {
        this.port = await navigator.serial.requestPort({})
      }

      // 等待串口打开
      try {
        await this.port.open({
          baudRate: 9600, // 波特率
          dataBits: 8, // 每帧的数据位数(7或8)
          stopBits: 1, // 停止位数(1或2)
          parity: 'none', // 校验模式，可以是none，偶数，奇数
          flowControl: 'none' // 流控模式(none或hardware)。
        })
      } catch (e) {
        console.log(e)
      }

      this.startMonitor(cfg)

    } else {

      Vue.prototype.$message({
        type: 'error',
        message: Vue.prototype.$tt('label_serial_port_not_support') // '您的浏览器不支持串口连接'
      })
    }
  },

  async startMonitor(cfg) {

    const _this = this

    const decoder = new TextDecoder('utf-8');

    this.keepReading = true

    if (this.port) {

      try {
        this.reader = this.port.readable.getReader()
        // this.writer = this.port.writable.getWriter()

        cfg.connected()
        window.localStorage.setItem('auto_weight_type', 'CHS_D_R')

        Vue.prototype.$message({
          type: 'success',
          message: Vue.prototype.$tt('label_auto_weight_has_connected') // 电子称已连接
        })
      } catch (e) {
        Vue.prototype.$message({
          type: 'error',
          message: Vue.prototype.$tt('label_auto_weight_please_check')  //'获取串口状态失败，请确认串没有被占用'
        })
        cfg.connectFail()
        return
      }

      // 写入信号
      // this.writeInt = setInterval(async () => {
      //   await this.writer.write(new Uint8Array([5]))
      //   await this.writer.write(new Uint8Array([17]))
      // }, 400)

      while (_this.port.readable && this.keepReading) {
        try {

          let tmpArr = new Uint8Array([])

          while (true) {
            const {value, done} = await this.reader.read()
            if (done) {
              break
            }
            // 累加字节
            let mergedArray = new Uint8Array(tmpArr.length + value.length);
            mergedArray.set(tmpArr);
            mergedArray.set(value, tmpArr.length);
            tmpArr = mergedArray

            let splitIndex = -1
            for (let i = tmpArr.length-1; i >=0 ; i--) {
              if(tmpArr[i] == 61){
                splitIndex = i
                break;
              }
            }

            // 已读到完整数量
            if(splitIndex > 0){
              let subArr1 = tmpArr.subarray(0, splitIndex)
              let decodeStr = decoder.decode(subArr1.reverse());

              if(Math.random()<0.5){
                cfg.monitor(parseFloat(decodeStr)/1000)
              }

              let subArr2 = tmpArr.subarray(splitIndex+1)
              if(subArr2.length> 0){
                tmpArr = new Uint8Array(subArr2)
              }
              else{
                tmpArr = new Uint8Array([])
              }
            }
          }
        } catch (error) {
          console.error(error)
        } finally {
          this.reader.releaseLock()
        }
      }

      // clearInterval(this.writeInt)
      await this.port.close()
    }
  },

  async close() {

    this.keepReading = false

    if (this.port) {

      try {
        this.reader.releaseLock()
      } catch (e) {
      }
      try {
        this.port.close()
      }catch (e){
      }

      this.port = null

      Vue.prototype.$message({
        type: 'info',
        message: Vue.prototype.$tt('label_auto_weight_has_disconnected') // 电子称已断开连接
      })
      window.localStorage.removeItem('auto_weight_type')

    }

  }

  //


}

